$(document).ready(function() {
    checkEnvironment();
    $('#tableUsers').dataTable({
        aoColumns: [
            {
                mData:  'user'
            }, {
                mData:  'role'
            }
        ],
        bDeferRender: true,
        bDestroy: true,
        sDom: 't',
        aaData: [
            {
                user:       'super',
                role:       'SUPERADMIN',
                password:   'super'
            }, {
                user:       'ca',
                role:       'CAPACITYADMIN',
                password:   'password'
            }
        ],
        fnCreatedRow: function(row, data, dataIndex) {
            $(row).unbind('click').bind('click', function() {
                login(data.user, data.password);
            });
        },
        fnDrawCallback: function(asettings) {
            $($('#tableUsers').dataTable().fnGetNodes()).css('cursor', 'pointer');
        }
    });
});

function login(username, pw) {
    $.ajax({
        type: "POST",
        async: false,
        url: 'j_security_check',
        data: {
            j_username: username,
            j_password: pw
        },
        success: function() {
            initSession(username, pw);
//            window.location.href = sessvars.guiURL + '/' + role + '/mitt_utbud.html';
            window.location.reload();
        },
        error: function() {
            alert("Fel användarnamn eller lösenord");
        }
    });
}

function initSession(username, password) {
    $.ajax({
        url: sessvars.guiURL + '/rest/users/' + username,
        type: 'GET',
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json',
        async: false,
        success: function(data) {
            if (data.role === "SUPERADMIN") {
                role = 'sa';
            } else if (data.role === "CAREUNITADMIN") {
                role = 'cua';
            }
            loggedIn = true;

            sessvars.username = username;
            sessvars.role = data.role;
            sessvars.realname = data.realname;
            sessvars.email = data.email;
            sessvars.password = password;
            sessvars.careUnits = data.careUnits;
            if($.cookie('kakvar') === undefined) {
                $.cookie('kakvar', 10, { expires: 365, path:'/' });
            }
        },
        error: function() {
            alert("Fel vid hämtning av profil");
        }
    });
}

function checkEnvironment() {
    var href = window.location.href.split('/');
    var baseURL = href[0] + '//' + href[2] + '/';

    sessvars.capacityURL = baseURL + "capacity";
    sessvars.productURL = baseURL + "product";
    sessvars.offersURL = baseURL + "offers";
    sessvars.guiURL = baseURL + "gui";
    sessvars.idmapURL = baseURL + "idmap";
}
